(function(i) {
    var t = setInterval(function () {
	if (document.readyState=="loaded"||document.readyState=="complete")
            clearInterval(t), i();
        }, 0);
})(initFrame);

var callbackId='';

var sel;

function setCallbackId() {
    var iframes=top.document.getElementsByTagName('iframe');
    if(iframes) {
    	for(var i=0; i<iframes.length; ++i) {
            if(iframes[i].contentWindow==this) {
	        	callbackId=iframes[i];
	        	break;
	    	}
        }
    }
    var frames=top.document.getElementsByTagName('frame');
    if(frames) {
        for(var i=0; i<frames.length; ++i) {
	    	if(frames[i].contentWindow==this) {
                callbackId=frames[i];
                break;
            }

        }
    }
}

function initFrame() {
    document.addEventListener('dragstart', function(ev) {
        sel = document.getSelection().toString().trim();
        if(sel.length==0) {
	    	return;
        }
        var fakeEvent={screenX: ev.screenX, screenY:ev.screenY, x:ev.x, y:ev.y, offsetX:ev.offsetX, offsetY:ev.offsetY};
        try {
        	setCallbackId();
        	top.frame_dragstart({callbackId:callbackId, sel:sel, event:fakeEvent});
        } catch (e) {
			safari.self.tab.dispatchMessage("frame_dragstart", {href:window.location.href, sel:sel, event:fakeEvent});
        }
    }, true);

    document.addEventListener('dragend', onMouseUp, true);
}

function onMouseUp() {
	if(top.document==undefined) {
		safari.self.tab.dispatchMessage("frame_dragend", "");
	} else {
		top.onMouseUp();
	}
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}